
package com.shop.cloud.mall.api.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.cloud.common.core.constant.CacheConstants;
import com.shop.cloud.mall.api.service.UserGradeConfigService;
import com.shop.cloud.mall.api.service.UserInfoService;
import com.shop.cloud.mall.common.entity.UserGradeConfig;
import com.shop.cloud.mall.common.entity.UserInfo;
import com.shop.cloud.mall.common.entity.UserPoints;
import com.shop.cloud.mall.api.mapper.UserPointsMapper;
import com.shop.cloud.mall.api.service.UserPointsService;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.klock.annotation.Klock;
import org.springframework.boot.autoconfigure.klock.model.LockTimeoutStrategy;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

/**
 * 用户积分
 *
 * @author
 * @date 2023-11-23 10:30:39
 */
@Service
@AllArgsConstructor
public class UserPointsServiceImpl extends ServiceImpl<UserPointsMapper, UserPoints> implements UserPointsService {

    private final UserGradeConfigService userGradeConfigService;
    private final UserInfoService userInfoService;

    @Override
    @CacheEvict(value = CacheConstants.APP_USER_INFO_CACHE, key = "#userId")
    @Klock(name = "updateUserPoints", keys = {"#userId"}, lockTimeoutStrategy = LockTimeoutStrategy.FAIL_FAST)
    public void updateUserPoints(String userId, Integer posts, Boolean addAccrue) {
        //增加当前积分
        String sql = " points_current = points_current + " + posts;
        if(addAccrue){
            //增加累积积分
            sql = sql + " , points_accrue = points_accrue + " + posts;
        }
        //如果是加积分，判断是否升级会员等级
        if(posts > 0){
            UserPoints userPoints = this.getById(userId);
            //当前累积积分数
            int nowPointsAccrue = userPoints.getPointsAccrue() + posts;
            UserInfo userInfo = userInfoService.getById(userId);
            int nextUserGrade = userInfo.getUserGrade() + 1;
            //查出下个等级需解锁积分数
            UserGradeConfig userGradeConfig = userGradeConfigService.getByGrade(nextUserGrade);
            if(userGradeConfig != null && userGradeConfig.getDeblockingValue() <= nowPointsAccrue){
                //更新用户会员等级
                userInfo.setUserGrade(nextUserGrade);
                userInfoService.updateById(userInfo);
            }
        }
        //更新积分
        this.update(new UserPoints(), Wrappers.<UserPoints>lambdaUpdate()
                .eq(UserPoints::getUserId, userId)
                .setSql(sql));
    }
}
